# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packagetool import PackageTool
from proto import Proto, Platform
import time


class DeployContext:
    @staticmethod
    def gi():
        if not hasattr(DeployContext, "_instance"):
            DeployContext._instance = DeployContext()
        return DeployContext._instance

    def __init__(self):
        self.progress = 0
        pass

    def deploy_context_ret(self, ret_callback, progress, msg):
        pt_ret = PackageTool()
        pt_ret.put_string("deploy_context_ret")
        pt_ret.put_float32(progress)
        pt_ret.put_string(msg)
        ret_callback(pt_ret)

    def on_download(self, url, size, data):
        self.df = {"url": url, "size": size, "data": data}

    def download(self, url, write_path):
        self.df = None
        Proto.download_file(url, self.on_download)
        for i in range(1000):
            if not self.df:
                time.sleep(0.1)
        if not self.df:
            return False
        with open(write_path, "wb") as f:
            f.write(self.df["data"])
        return True

    def start(self, ros_type, ret_callback):
        if self.progress > 0:
            return
        self.progress = 1
        self.deploy_context_ret(ret_callback, 1.0, "正在检查系统环境...")
        if ros_type == "ros1":
            if Platform.is_ubuntu_20_04():
                self.deploy_context_ret(ret_callback, 5.0, "正在下载安装包...")
                self.download("aaa/bbb/ccc.tar.gz", "/tmp/ccc.tar.gz")
            elif Platform.is_ohos():
                self.deploy_context_ret(ret_callback, 5.0, "正在下载安装包...")
                self.download("aaa/bbb/ccc.tar.gz", "/data/local/tmp/ccc.tar.gz")
            else:
                self.deploy_context_ret(
                    ret_callback,
                    -1,
                    "系统环境不满足要求，ros1只能部署在Ubuntu 20.04或OpenHarmony上",
                )
                return
        elif ros_type == "ros2":
            pass
        elif ros_type == "dora":
            pass
